package com.herench.jwt.controller;

import com.herench.jwt.annotation.Authorization;
import com.herench.jwt.annotation.CurrentUser;
import com.herench.jwt.config.ResultStatus;
import com.herench.jwt.model.ResultModel;
import com.herench.jwt.model.TokenModel;
import com.herench.jwt.model.User;
import com.herench.jwt.service.TokenService;
import com.herench.jwt.service.UserService;
import com.herench.jwt.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;


/**
 * 获取和删除token的请求地址，在Restful设计中对应资源映射
 *
 * @author Squall
 * @create 12/03/2018
 * @since 1.0.0
 */


@RestController
@RequestMapping("/tokens")
public class TokenController {

    @Autowired
    private UserService userService;

    @Autowired
    private TokenService tokenService;

    @RequestMapping(method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public ResponseEntity login(@RequestParam String username, @RequestParam String password) {
//        Assert.notNull(username, "username can not be empty");
//        Assert.notNull(password, "password can not be empty");

        User user = userService.findByUsername(username);
        if (user == null ||  //未注册
                !user.getPassword().equals(password)) {  //密码错误
            //提示用户名或密码错误
            return new ResponseEntity(JsonUtil.beanToJson(ResultModel.error(ResultStatus.USERNAME_OR_PASSWORD_ERROR)), HttpStatus.NOT_FOUND);


        }

        //生成一个token，保存用户登录状态
        TokenModel tokenModel = tokenService.createToken(user.getId());
        return new ResponseEntity(JsonUtil.beanToJson(ResultModel.ok(tokenModel)), HttpStatus.OK);
    }


    @RequestMapping(method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    @Authorization
    @ResponseBody
    public ResponseEntity isloged(@CurrentUser User user) {
        if (user.getId() == 0)
            return new ResponseEntity(JsonUtil.beanToJsonString(ResultModel.error(ResultStatus.USER_NOT_LOGIN)), HttpStatus.OK);

        //Token 登录有效
        return new ResponseEntity(JsonUtil.beanToJsonString(ResultModel.ok()), HttpStatus.OK);

    }


    @RequestMapping(method = RequestMethod.DELETE, produces = "text/html;charset=UTF-8")
    @Authorization
    @ResponseBody
    public ResponseEntity logout(@CurrentUser User user) {
        if (user.getId() == 0)
            return new ResponseEntity(JsonUtil.beanToJson(ResultModel.error(ResultStatus.USER_NOT_FOUND)), HttpStatus.OK);

        tokenService.deleteToken(user.getId());
        return new ResponseEntity(JsonUtil.beanToJson(ResultModel.ok()), HttpStatus.OK);

    }

}
